//
//  LCRdListenViewController.m
//  YinYueTai
//
//  Created by CongCong on 15-7-19.
//  Copyright (c) 2015年 CongCong. All rights reserved.
//把这个 设置成单例

#import "LCRdListenViewController.h"

@interface LCRdListenViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic) LCMusicInfoModel *listenModel;
@property (nonatomic) LCRdPlayInfo *currentModel;
@property (nonatomic) UIPageControl *pageView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIView *buttonView;
- (IBAction)prior:(id)sender;

- (IBAction)play:(id)sender;

- (IBAction)next:(id)sender;
@end

@implementation LCRdListenViewController
+ (id)shareListen
{
    static id shareObject=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareObject = [[self alloc]init];
    });
    return shareObject;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self fetchWebDataWith:kMusicDetailUrl body:[NSString stringWithFormat:kMusicDetailBody,self.playInfoModel.tingid]];
    self.currentModel = self.playInfoModel;
    [self startPlayMusicWithUrl:self.playInfoModel.musicUrl];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"viewapper");
    
    if ([self.playInfoModel.musicUrl isEqualToString: self.currentModel.musicUrl]) {
        return;
    }
    else
    {
        self.index--;
        [self next:nil];
        [self fetchWebDataWith:kMusicDetailUrl body:[NSString stringWithFormat:kMusicDetailBody,self.playInfoModel.tingid]];
    }
}
- (void)startPlayMusicWithUrl:(NSString *)url
{
    [AFSoundManager sharedManager].isPlaying = YES;
    self.currentModel = self.playInfoModel;
    __weak typeof(self) weakSelf = self;
    [[AFSoundManager sharedManager]startStreamingRemoteAudioFromURL:url andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished)
    {
        if (!error)
        {
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"mm:ss"];
            NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
            weakSelf.timeRemaining.text = [formatter stringFromDate:timeRemainingDate];
            if ([weakSelf.timeRemaining.text isEqualToString:@"00:00"]) {
                [weakSelf next:nil];
            }
            NSLog(@"%@",weakSelf.timeRemaining.text);
            weakSelf.slider.value = percentage * 0.01;
        } else
        {
            NSLog(@"There has been an error playing the remote file: %@", [error description]);
        }
    }];
}
- (void)initJosnModelWith:(NSDictionary *)dataDict
{
    NSDictionary *dict = dataDict[@"data"];
    self.listenModel  = [[LCMusicInfoModel alloc]initWithDictionary:dict error:nil];
    [self.collectionView reloadData];
    
}
- (void)initUI
{
    [self.playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateSelected];
    self.scrollView.contentSize = CGSizeMake(kScreenSize.width*4, 0);
    self.scrollView.userInteractionEnabled = YES;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentOffset = CGPointMake(kScreenSize.width, 0);
    _scrollView.delegate = self;
    self.pageView = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, self.buttonView.frame.size.width, 8)];
    
    self.pageView.pageIndicatorTintColor = [UIColor brownColor];
    self.pageView.numberOfPages = 4;
    self.pageView.currentPage = 1;
    self.pageView.backgroundColor = [UIColor grayColor];
    
    [self.buttonView addSubview:self.pageView];
    
    [self firstView];
    [self secondView];
    [self thirdView];
    [self lastView];
}

//-(void)backOrForwardAudio:(UISlider *)sender {
//    
//    [[AFSoundManager sharedManager]moveToSection:sender.value];
//}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // NSLog(@"%f",scrollView.contentOffset.x);
    self.pageView.currentPage = scrollView.contentOffset.x/kScreenSize.width;
}
- (void)firstView
{
    self.tabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height-104)];
    [self.tabView registerNib:[UINib nibWithNibName:@"LCRdListenListCell" bundle:nil] forCellReuseIdentifier:@"LCRdListenListCell"];
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.scrollView addSubview:self.tabView];
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.musicArray.count;
    
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LCRdListenListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LCRdListenListCell" forIndexPath:indexPath];
    LCRdDetailListModel *model = self.musicArray[indexPath.row];
    [cell showModel:model];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LCRdDetailListModel *model = self.musicArray[indexPath.row];
    self.playInfoModel = model.playInfo;
    [self addImageForMusicImage];
    [self addTextForTextView];
    [self startPlayMusicWithUrl:model.musicUrl];
    self.index = indexPath.row;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (void)secondView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(kScreenSize.width, 0, kScreenSize.width, kScreenSize.height-kScreenSize.height/662*40)];
    view.backgroundColor = [UIColor clearColor];
    self.musicImage = [[UIImageView alloc]initWithFrame:CGRectMake(50, 100, kScreenSize.width-100, kScreenSize.width-100)];
    [self addImageForMusicImage];
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, kScreenSize.width+10, kScreenSize.width-100, 40)];
    self.titleLabel.text = self.playInfoModel.title;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:self.titleLabel];
    self.slider = [[TLTiltSlider alloc]initWithFrame:CGRectMake(50, kScreenSize.width+85, kScreenSize.width-100, 40)];
    [_slider addTarget:self action:@selector(backOrForwardAudio:) forControlEvents:UIControlEventValueChanged];
    self.timeRemaining = [[UILabel alloc]initWithFrame:CGRectMake(kScreenSize.width-110, kScreenSize.width+50, 60, 40)];
    self.timeRemaining.text = @"00:00";
    [view addSubview:self.timeRemaining];
    _slider.value = 0;
    self.timeRemaining.textAlignment = NSTextAlignmentRight;
    [view addSubview:self.musicImage];
    [view addSubview:self.slider];
    [self.scrollView addSubview:view];
    
}
-(void)backOrForwardAudio:(UISlider *)sender {
    
    [[AFSoundManager sharedManager]moveToSection:sender.value];
}
- (void)addImageForMusicImage
{
    [self.musicImage sd_setImageWithURL:[NSURL URLWithString:self.playInfoModel.imgUrl] placeholderImage:[UIImage imageNamed:@"hoder"]];
    self.titleLabel.text = self.playInfoModel.title;
}
- (void)thirdView
{
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(kScreenSize.width*2, 64, kScreenSize.width, kScreenSize.height-104)];
    _textView.editable = NO;
    _textView.selectable = NO;
    _textView.backgroundColor = [UIColor clearColor];
    [self addTextForTextView];
        _tabView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:_textView];
}
- (void)addTextForTextView
{
    NSString *webString = [NSString stringWithContentsOfURL:[NSURL URLWithString:self.playInfoModel.webview_url] encoding:NSUTF8StringEncoding error:nil];
    NSMutableString *textString = [[NSMutableString alloc]init];
    if (webString)
    {
        OCGumboDocument *document = [[OCGumboDocument alloc]initWithHTMLString:webString];
        NSArray *rows = document.body.Query(@"article.typo").find(@"p");
        for (OCGumboElement *obj in rows) {
            [textString appendString:[NSString stringWithFormat:@"%@\n",obj.text()]];
        }
    }
    
    _textView.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:20];
    _textView.text = textString;

}
- (void)lastView
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 2, 0, 2);
    self.flowLayout.minimumLineSpacing = 1;
    self.flowLayout.minimumInteritemSpacing = 1;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScreenSize.width*3,64, kScreenSize.width, kScreenSize.height-104) collectionViewLayout:self.flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.collectionView.frame];
    imageView.image = [UIImage imageNamed:@"bgView"];
    self.collectionView.backgroundView = imageView;
    
    [self.scrollView addSubview:self.collectionView];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    [self registerNib];
    
}
- (void)registerNib
{
    [self.collectionView registerNib:[UINib nibWithNibName:@"LCMoreTingCell" bundle:nil] forCellWithReuseIdentifier:@"LCMoreTingCell"];
    
}
#pragma mark - <UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.listenModel.moreting.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LCMoreTingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LCMoreTingCell" forIndexPath:indexPath];
    LCMoreTingModel *model = self.listenModel.moreting[indexPath.row];
    [cell showModel:model];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenSize.width-8)/3, (kScreenSize.width-8)/3);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //点击事件
    
    [self.musicArray removeAllObjects];
    for (LCMoreTingModel *model  in self.listenModel.moreting) {
        LCRdDetailListModel *detail = [[LCRdDetailListModel alloc]init];
        detail.title = model.title;
        detail.coverimg = model.coverimg;
        detail.playInfo = model.playInfo;
        detail.musicUrl = model.playInfo.musicUrl;
        [self.musicArray addObject:detail];
    }
    [self.tabView reloadData];
    self.playInfoModel = [self.musicArray[indexPath.row] playInfo];
    [self addImageForMusicImage];
    [self addTextForTextView];
    [self startPlayMusicWithUrl:self.playInfoModel.musicUrl];
    self.index = indexPath.row;
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *header;
    if([kind isEqual:UICollectionElementKindSectionHeader])
    {
       
        header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
        if (!self.listenModel) {
            return header;
        }
        UILabel *oldLabel = (UILabel*)[header viewWithTag:301];
        [oldLabel removeFromSuperview];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height/662*150)];
        label.numberOfLines = 0;
        label.tag = 301;
        NSString *string = [NSString stringWithFormat:@"主播：%@\n \n作者：%@\n\n主播的其他作品：",self.listenModel.userinfo.uname,self.listenModel.authorinfo.uname];
        label.text = string;
        [header addSubview:label];
    }
    return header;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(kScreenSize.width, kScreenSize.height/662*150);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)prior:(id)sender {
    //NSLog(@"paly");
    self.index-=1;
    if (self.index<0) {
        self.index = self.musicArray.count-1;
    }
    LCRdDetailListModel *model = self.musicArray[self.index];
    self.playInfoModel = model.playInfo;
    [self addImageForMusicImage];
    [self addTextForTextView];
    [self startPlayMusicWithUrl:model.musicUrl];
}
- (IBAction)play:(id)sender {
    self.playButton.selected = !self.playButton.selected;
    NSLog(@"paly");
    if (self.playButton.selected) {
        [[AFSoundManager sharedManager]pause];
    }
    else
    {
        [[AFSoundManager sharedManager]resume];
    }
}
- (void)nextMusic
{
    [self next:nil];
}
- (void)priorMusic
{
    [self prior:nil];
}
- (IBAction)next:(id)sender {
    self.index+=1;
    if (self.index>=self.musicArray.count) {
        self.index = 0;
    }
    LCRdDetailListModel *model = self.musicArray[self.index];
    self.playInfoModel = model.playInfo;
   
        [self addImageForMusicImage];
        [self addTextForTextView];
    
    [self startPlayMusicWithUrl:model.musicUrl];
}
-(void)dealloc
{
    NSLog(@"销毁");
}
@end
